package nashorn;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;

public class Test {
    public static final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    public static final ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
    private final static Logger log = LogManager.getLogger(Test.class);
    public static WatchService watchService = null;

    public static void doMonitor() {
        try {
            while (true) {
                WatchKey key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    Kind<?> kind = event.kind();
                    log.info(() -> "Event on " + event.context().toString() + " is " + kind);
                    doMonitorFile();
                }
                boolean reset = key.reset();//重置Key
                if (!reset) {//假如重置失败，则退出监控
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void doMonitorFile() throws Exception {
        URL url = Thread.currentThread().getContextClassLoader().getResource("business.js");
        URI uri = url.toURI();
        File file = new File(uri);
        log.info(() -> "获取的URL:" + url);
        Reader reader = new FileReader(file);
        Bindings scope = nashorn.createBindings();
        Map<String, String> map = new HashMap<>();
        map.put("asd", "345");
        scope.put("jss", map);
        nashorn.eval(reader, scope);
    }

    public static void main(String[] args) throws Exception {
        //初始化调用文件
        doMonitorFile();
        watchService = FileSystems.getDefault().newWatchService();
        URI dirURI = Thread.currentThread().getContextClassLoader().getResource("").toURI();
        Path path = Paths.get(dirURI);
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        doMonitor();
    }

}
